package loginauth

import (
	"a-common/config"
	"log/slog"
	"time"

	"github.com/golang-jwt/jwt/v5"
)

type JwtClaims struct {
	ID     int64
	Name   string
	Device string
	Role   string
	jwt.RegisteredClaims
}

// CreateShortToken 创建短Token
func CreateShortToken(id int64, name, device, ip string) (string, error) {
	duration, err := time.ParseDuration(config.Config.Login.Token.Ttl)
	if err != nil {
		return "", err
	}
	return createToken(id, name, device, ip, "Token", duration)
}

// CreateLongToken 创建长Token
func CreateLongToken(id int64, name, device, ip string) (string, error) {
	duration, err := time.ParseDuration(config.Config.Login.Token.Ttl)
	if err != nil {
		return "", err
	}
	return createToken(id, name, device, ip, "RefToken", duration)
}

// AuthToken 认证Token
func AuthToken(token, ip string) (id int64, name string, device string, role string) {
	cla, err := jwt.ParseWithClaims(token, &JwtClaims{}, func(token *jwt.Token) (interface{}, error) {
		return []byte(config.Config.Login.Token.Salt + ip), nil
	})
	if err != nil {
		slog.Error(err.Error())
		return 0, "", "", ""
	}
	if claims, ok := cla.Claims.(*JwtClaims); ok && cla.Valid {
		s, e := claims.GetSubject()
		if e == nil && s == "Token" {
			return claims.ID, claims.Name, claims.Device, ""
		}
	}
	return 0, "", "", ""
}

// CreateToken 创建令牌
func createToken(id int64, name, device, ip, subject string, ttl time.Duration) (string, error) {
	nowTime := time.Now()
	iJwtClaims := JwtClaims{
		ID:     id,
		Name:   name,
		Device: device,
		RegisteredClaims: jwt.RegisteredClaims{
			// 主题
			Subject: subject,
			// 发行者
			Issuer: "aijuan",
			// 签发时间
			IssuedAt: jwt.NewNumericDate(nowTime),
			// 过期时间
			ExpiresAt: jwt.NewNumericDate(nowTime.Add(ttl)),
		},
	}
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, iJwtClaims)

	// 加密 密钥+IP地址，防止滥用token
	return token.SignedString([]byte(config.Config.Login.Token.Salt + ip))
}
